package com.hg.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

/**
 * @Author: skh
 * @Date: 2019/10/25 16:38
 * @Description:
 */
public class ZookeeperDemo {

    private static          ZooKeeper zooKeeper ;
    public static void main(String[] args) throws KeeperException, InterruptedException {
        try {
            zooKeeper = new ZooKeeper("47.98.129.125:2181", 2000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println("监听成功");
                    try {
                        //保证持续监听,因为每次进入方法就会设置watch为true.
                        getData();
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> children = zooKeeper.getChildren("/", null);
        System.out.println("children = " + children);
        getData();
        Thread.sleep(Integer.MAX_VALUE);
    }

    private static void getData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/demo1",true,null);
        System.out.println(new String(data));
    }

    private static void createNode(ZooKeeper zooKeeper) {
        try {
            String path = zooKeeper.create("/demo1", "skh".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("path = " + path);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
